package com.hongshan.wallet.core.home

import android.content.Context
import android.graphics.Rect
import android.support.design.widget.CoordinatorLayout
import android.support.v4.view.ViewCompat
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.AttributeSet
import android.view.View


/**
 * Copyright Qiandai Ltd.
 * Copyright (c) 2019
 * All rights reserved
 *
 * @project  : Wallet
 * @package  : com.example.wallet.core.home
 * @author   : Administrator
 * @data     : 2019/3/20
 * @email    : zhangxx@baihang-china.com
 */
class HeaderBehavior @JvmOverloads constructor(context: Context? = null, attrs: AttributeSet? = null) :
    CoordinatorLayout.Behavior<View>(context, attrs) {

    var rvBottom = 0

    // 列表上一个全部可见的item位置
    private var lastPosition = 0

    override fun onStartNestedScroll(
        coordinatorLayout: CoordinatorLayout,
        child: View,
        directTargetChild: View,
        target: View,
        axes: Int,
        type: Int
    ): Boolean {
        return axes and ViewCompat.SCROLL_AXIS_VERTICAL != 0
    }

    override fun onNestedPreScroll(
        coordinatorLayout: CoordinatorLayout,
        child: View,
        target: View,
        dx: Int,
        dy: Int,
        consumed: IntArray,
        type: Int
    ) {
        super.onNestedPreScroll(coordinatorLayout, child, target, dx, dy, consumed, type)
        if (target is RecyclerView) {
            val rect = Rect()
            target.getLocalVisibleRect(rect)
            val bottom = rect.bottom
            if (bottom == rvBottom && dy > 0){
                return
            }
            rvBottom =if (dy<0) 0 else bottom
            val linearLayoutManager = target.layoutManager as LinearLayoutManager
            val pos = linearLayoutManager.findFirstCompletelyVisibleItemPosition()
            val canScroll = canScroll(child, dy.toFloat())
            if (canScroll && pos == 0) {
                var finalY = child.translationY - dy
                if (finalY < -child.height) {
                    finalY = (-child.height).toFloat()
                } else if (finalY > 0) {
                    finalY = 0f
                }
                child.translationY = finalY
                // 让CoordinatorLayout消费滑动事件
                consumed[1] = dy
            }
            lastPosition = pos
//            83d4c93789fe9480c72e149bab82a3d48e0f063f
        }
    }

    private fun canScroll(child: View, scrollY: Float) =
        !(scrollY > 0 && child.translationY == (-child.height).toFloat())
}